﻿using Great_Eggspectations.DAL;
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Great_Eggspectations.ViewModels
{
    public class TransactionsIndexTableViewModel
    {
        public decimal Credits { get; private set; }
        public decimal PartnerCredits { get; private set; }
        public decimal NetCredits
        {
            get { return Credits - PartnerCredits; }
        }
        public decimal Debits { get; private set; }
        public decimal NetProfits
        {
            get { return NetCredits - Debits; }
        }
        public IPagedList<Transaction> TransactionsPagedList { get; private set; }

        public TransactionsIndexTableViewModel(IEnumerable<Transaction> transactions, int pageNumber = 1, int pageSize = 25)
        {
            var sales = transactions.Where(t => t.IsSale);
            var purchases = transactions.Where(t => !t.IsSale);
            var partners = transactions.Select(t => t.Partner).Distinct();
            var partnersWithCredit = partners.Where(p => p.Balance > 0.0m);

            Credits = sales.Any() ? (decimal) sales.Sum(t => t.Payment) : 0.0m;
            PartnerCredits = partnersWithCredit.Any() ? partnersWithCredit.Sum(p => p.Balance) : 0.0m;
            Debits = purchases.Any() ? (decimal)purchases.Sum(t => t.Payment) : 0.0m;
            
            TransactionsPagedList = new PagedList<Transaction>(transactions.OrderByDescending(t => t.Date), pageNumber, pageSize);
        }
    }
}